package com.happyscan138.makefun;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.happyscan138.makefun.BaseAdapter.Comment_item;
import com.happyscan138.makefun.Urls.Urls;
import com.happyscan138.makefun.View.ListViewForScrollView;
import com.happyscan138.makefun.View.RoundImageView;
import com.happyscan138.makefun.adapter.CommentAdapter;
import com.happyscan138.makefun.adapter.VideoComAdapter;
import com.happyscan138.makefun.base.VideoPlayView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestHandle;
import com.loopj.android.http.RequestParams;
import com.squareup.picasso.Picasso;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

import static com.happyscan138.makefun.Land.api;
import static com.happyscan138.makefun.Urls.Urls.Share;
import static com.happyscan138.makefun.Urls.Urls.base;
import static com.happyscan138.makefun.base.http.client;
import static com.happyscan138.makefun.base.http.params;
import static com.loopj.android.http.AsyncHttpClient.log;

/**
 * Created by Administrator on 2017/3/1.
 */

public class VideoDetail extends Activity implements View.OnClickListener {
    private SharedPreferences preferences;
    public String access_key;
    public String problem_id;
    private  Intent intent;
    private TextView nick_Name,VideoTime,VideoText;
    private RoundImageView VideoHead;
    private TextView ReadCount,CommentCount,AdmireCount;
    private TextView share,Comment, Good,ShouCang;
    private PopupWindow pop;
    private LayoutInflater inflater;
    private String url,WXtitle,WXdescription;
    public LinearLayout CommentLinearalayout;
    private int tag;
    private RequestParams params2;
    private List<Comment_item> list;
    private Comment_item data;
    private VideoComAdapter adapter;
    public int positionUserId;
    private ListViewForScrollView listViewcomment;
    private Button btnSendComment ;
    private int atUserId=-1;
    public String comment;
    private EditText editTextComment;
    private String like_type_id;
    private String Thumb;
    private ImageView Img;
    private int commentNum;
    private int admireNum;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.videodetailed);
        preferences = getSharedPreferences("UserInfo", MODE_PRIVATE);
        access_key=preferences.getString("UserId","");
        intent=getIntent();
        problem_id=intent.getStringExtra("problem_id");
        inflater = LayoutInflater.from(this);
        like_type_id=preferences.getString("LikeTypeID","");
        initView();
        getNetData();
        getCommentNetData();
    }

    public void initView(){
        TextChange  change=new TextChange();
        VideoHead=(RoundImageView)findViewById(R.id.VideoDigital_head);
        nick_Name=(TextView)findViewById(R.id.VideoDigital_name);
        VideoTime=(TextView)findViewById(R.id.VideoDigital_time);
        VideoText=(TextView)findViewById(R.id.Question_text);
        ReadCount=(TextView)findViewById(R.id.Video_read);
        CommentCount=(TextView)findViewById(R.id.Video_comment);
        AdmireCount=(TextView)findViewById(R.id.Video_count);
        share=(TextView)findViewById(R.id.Videoshare);
        share.setOnClickListener(this);
        Comment=(TextView)findViewById(R.id.Videocomment);
        Comment.setOnClickListener(this);
        CommentLinearalayout=(LinearLayout)findViewById(R.id.video_input_comment) ;
        listViewcomment=(ListViewForScrollView)findViewById(R.id.video_listView_inputComment);
        btnSendComment=(Button)findViewById(R.id.video_send_comment);
        btnSendComment.setOnClickListener(this);
        editTextComment=(EditText)findViewById(R.id.video_input);
        editTextComment.addTextChangedListener(change);
        Good=(TextView)findViewById(R.id.Videodianzan);
        Good.setOnClickListener(this);
        ShouCang=(TextView)findViewById(R.id.Videoshoucang);
        ShouCang.setOnClickListener(this);
        Img=(ImageView)findViewById(R.id.video_img);
    }
    public void getNetData(){
        client=new AsyncHttpClient();
        params=new RequestParams();
        params.put("access_key",access_key);
        params.put("problem_id",problem_id);
        log.e("videoparams",params.toString());
        RequestHandle handle=client.post(Urls.AnswerList,params,new JsonHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                log.e("onSuccess",response.toString());
                String jsonStr=response.toString();
                try {
                    JSONObject jsonObject=new JSONObject(jsonStr);
                    JSONObject data=jsonObject.getJSONObject("data");
                    String head=base+data.getString("img_path");
                    String nickName=data.getString("nick_name");
                    String time=data.getString("create_date");
                    String text=data.getString("content");
                    final String resource=base+data.getString("resource");
                    Thumb=base+data.getString("thumb");
                    String read=data.getString("read_count");
                    String m3u8=base+data.getString("m3u8_file");
                    log.e("path",m3u8);
                     commentNum=data.getInt("comment_count");
                     admireNum=data.getInt("comment_count");

                    //赋值
                    Picasso.with(VideoDetail.this).load(head).into(VideoHead);
                    nick_Name.setText(nickName);
                    VideoTime.setText(time);
                    VideoText.setText(text);
                    if(m3u8.equals(Urls.base)){
                        replaceVieo(resource);
                    }else {
                        replaceVieo(m3u8);
                    }

                    if(Thumb.equals(Urls.base)){
                        Img.setImageDrawable(getResources().getDrawable(R.mipmap.makefun));
                    }else {
                        Picasso.with(VideoDetail.this).load(Thumb).into(Img);
                    }
                    ReadCount.setText(read);
                    CommentCount.setText(commentNum+"");
                    AdmireCount.setText(admireNum+"");

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                log.e("onFailure",responseString);
            }
        });
    }
    private void getCommentNetData(){
        params2=new RequestParams();
        params2.put("type_key_val",problem_id);
        params2.put("page_count","10");
        params2.put("com_id_index","0");
        params2.put("type_id","1");
        log.e("paramscomment",params2.toString());
        RequestHandle handle=client.post(Urls.CommentList,params2,new JsonHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                log.e("getCommentNetDataonSuccess",response.toString());
                list=new ArrayList<Comment_item>();
                String jsonStr=response.toString();
                try {
                    JSONObject  jsonObject=new JSONObject(jsonStr);
                    JSONArray jsonArray=jsonObject.getJSONArray("data");
                    for (int i=0;i<jsonArray.length();i++){
                        JSONObject objectData=jsonArray.getJSONObject(i);
                        data=new Comment_item();
                        data.head=base+objectData.getString("img_path");
                        data.name=objectData.getString("nick_name");
                        data.time=objectData.getString("com_date");
                        data.text=objectData.getString("comment");
                        data.User_ID=objectData.getString("user_id");
                        list.add(data);
                        log.e("list",list.size()+"");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                adapter=new VideoComAdapter(VideoDetail.this,list);
                adapter.setOnItemAddClick(new CommentAdapter.OnAddClickListener() {
                    @Override
                    public void onItemClick(int positionID, int adatag) {
                        tag=adatag;
                        positionUserId=positionID;
                        log.e("adapterTag",tag+"");
                        log.e("positionUserId",positionUserId+"");

                    }
                });
                listViewcomment.setAdapter(adapter);
            }


            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                log.e("getCommentNetDataonFailure",responseString);
            }
        });
    }
    private void replaceVieo(final String path){
        ImageView play=(ImageView)findViewById(R.id.video_play_btn);
        final VideoPlayView playView=(VideoPlayView)findViewById(R.id.video_play_view);
        final FrameLayout showLayout=(FrameLayout)findViewById(R.id.video_show_layout);
        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                showLayout.setVisibility(View.GONE);
                playView.setUrl(path);
                playView.setThumb(Thumb);
             //   setPlayView(playView);
              //  playView.openVideo();
                playView.setVisibility(View.VISIBLE);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.Videoshare:
                // 引入窗口配置文件
                View viewpop = inflater.inflate(R.layout.share, null);
                pop = new PopupWindow(viewpop, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, false);

                pop.setTouchable(true);
                pop.setOutsideTouchable(true);
                pop.setFocusable(true);
                pop.update();
                pop.setBackgroundDrawable(new BitmapDrawable());
                Button friendnet = (Button) viewpop.findViewById(R.id.friendnet);
                friendnet.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        shareArticleToWx(1);

                    }
                });
                Button friend = (Button) viewpop.findViewById(R.id.friend);
                friend.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        shareArticleToWx(0);

                    }
                });
                pop.showAsDropDown(viewpop);
                break;
            case R.id.Videocomment:
                tag=1;
                log.e("tag",tag+"");
                CommentLinearalayout.setVisibility(View.VISIBLE);
                break;
            case R.id.video_send_comment:

                if(tag==1) {
                    atUserId=0;
                }else if(tag==2){
                    atUserId=positionUserId;
                    log.e("positionUserID",atUserId+"");
                }
                params = new RequestParams();
                params.put("access_key", access_key);
                params.put("comment", comment);
                params.put("type_key_val", problem_id);
                params.put("at_user_id",atUserId+"" );
                params.put("com_id", "0");
                params.put("type_id", "1");
                log.e("at_user_id", atUserId+"");
                RequestHandle handle1 = client.post(Urls.Comment, params, new JsonHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        super.onSuccess(statusCode, headers, response);
                        String jsonStr = response.toString();
                        try {
                            JSONObject data = new JSONObject(jsonStr);
                            String code = data.getString("code");
                            int a = Integer.valueOf(code).intValue();
                            if (a == 1) {
                                CommentLinearalayout.setVisibility(View.GONE);
                                getCommentNetData();
                                CommentCount.setText(++commentNum+"");
                                Toast.makeText(VideoDetail.this, "评论成功", Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        log.e("onSuccess", response.toString());
                    }
                });
                editTextComment.setText(null);
                break;
            case R.id.Videodianzan:
                RequestParams params3=new RequestParams();
                params3.put("access_key",access_key);
                params3.put("item_id",problem_id);

                log.e("params3",params3.toString());
                RequestHandle handle2=client.post(Urls.Dianzan,params3,new JsonHttpResponseHandler(){
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        super.onSuccess(statusCode, headers, response);
                        String jsonStr=response.toString();
                        try {
                            JSONObject jsonObject=new JSONObject(jsonStr);
                            String msg=jsonObject.getString("msg");
                            int a=jsonObject.getInt("code");
                            if(a==1){
                                AdmireCount.setText(++admireNum+"");
                            }
                            Toast.makeText(VideoDetail.this,msg,Toast.LENGTH_SHORT).show();

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                        super.onFailure(statusCode, headers, responseString, throwable);
                    }
                });
                break;
            case R.id.Videoshoucang:
                RequestParams params4 =new RequestParams();
                params4.put("access_key",access_key);
                params4.put("problem_id",problem_id);
                params4.put("like_type_id",like_type_id);
                log.e("shoucangparams",params4.toString());
                RequestHandle handle3=client.post(Urls.Like,params4,new JsonHttpResponseHandler(){
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        super.onSuccess(statusCode, headers, response);
                        String json=response.toString();
                        log.e("jsonsaaaaas",json);
                        try {
                            JSONObject jsonObject=new JSONObject(json);
                            String msg=jsonObject.getString("msg");
                            Toast.makeText(VideoDetail.this,msg,Toast.LENGTH_SHORT).show();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {

                        super.onFailure(statusCode, headers, responseString, throwable);
                        log.e("jsonsaaaaas",responseString);
                    }
                });

                break;

        }
    }
    private class TextChange implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            comment=editTextComment.getText().toString();
        }
    }
    private void shareArticleToWx(final int flag) {


        if (!api.isWXAppInstalled()) {
            Toast.makeText(VideoDetail.this, "未安装微信客户端，请先下载",
                    Toast.LENGTH_LONG).show();
            return;
        }
        RequestParams paramstoWX=new RequestParams();
        paramstoWX.put("problem_id",problem_id);
        RequestHandle handlWX=client.post(Share,paramstoWX,new JsonHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                String jsonStr=response.toString();
                try {
                    JSONObject jsonobj=new JSONObject(jsonStr);
                    JSONObject data=jsonobj.getJSONObject("data");
                    url=data.getString("url");
                    WXtitle="     "+data.getString("title");
                    WXdescription=data.getString("description");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        WXWebpageObject webpage=new WXWebpageObject();
        webpage.webpageUrl=url;
        WXMediaMessage msg= new WXMediaMessage(webpage);

        msg.title=WXdescription+WXtitle;
        Bitmap bitmap= BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher);
        msg.setThumbImage(bitmap);
        SendMessageToWX.Req req=new SendMessageToWX.Req();
        req.transaction=String.valueOf(System.currentTimeMillis());
        req.message=msg;
        req.scene=flag;
        api.sendReq(req);

    }
}
